"use server";

import { Player, PlayerTier, Region } from '@/types/player';

// 获取基础URL
const getBaseUrl = () => {
  // 在服务器端，需要提供完整URL
  if (typeof window === 'undefined') {
    // 检查环境变量中是否有API URL，如果没有则使用localhost
    return process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
  }
  // 在客户端，可以使用相对路径
  return '';
};

// 分数计算工具函数
const SCORE_MAP: Record<string, number> = {
  // 特殊模式基础分
  SWORD: 100,
  CRYSTAL: 90,
  BUHC: 85,
  POTION: 80,
  NPOT: 75,
  SMP: 70,
  
  // 等级加成分数
  HT1: 60,
  LT1: 45,
  HT2: 30,
  LT2: 20,
  HT3: 10,
  LT3: 6,
  HT4: 4,
  LT4: 3,
  HT5: 2,
  LT5: 1
};

// 获取所有玩家
export async function getPlayers(): Promise<Player[]> {
  try {
    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/api/players`);
    
    if (!response.ok) {
      throw new Error('Failed to fetch players');
    }
    
    const data = await response.json();
    return data;
  } catch (error: any) {
    console.error('获取玩家数据错误:', error);
    throw new Error(error.message || '获取玩家数据失败');
  }
}

// 获取玩家排名数据
export async function getRankings(mode?: string): Promise<any> {
  try {
    const baseUrl = getBaseUrl();
    const url = mode 
      ? `${baseUrl}/api/rankings?mode=${mode}`
      : `${baseUrl}/api/rankings`;
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error('Failed to fetch rankings');
    }
    
    const data = await response.json();
    return data;
  } catch (error: any) {
    console.error('获取排名数据错误:', error);
    throw new Error(error.message || '获取排名数据失败');
  }
}

// 通过名字查询玩家
export async function getPlayerByName(name: string) {
  const baseUrl = getBaseUrl();
  const response = await fetch(`${baseUrl}/api/player?name=${encodeURIComponent(name)}`);
  if (!response.ok) {
    throw new Error('无法找到该玩家');
  }
  return response.json();
}

// 添加新玩家
export async function addPlayer(playerData: {
  name: string;
  region?: string;
  avatar?: string;
  region_id?: string;
  region_color?: string;
  is_blacklisted?: boolean;
}): Promise<Player> {
  try {
    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/api/players`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(playerData),
    });
    
    if (!response.ok) {
      const error = await response.text();
      throw new Error(error || '添加玩家失败');
    }
    
    const data = await response.json();
    return data.player;
  } catch (error: any) {
    console.error('添加玩家错误:', error);
    throw new Error(error.message || '添加玩家失败');
  }
}

// 获取单个玩家
export async function getPlayerById(id: string): Promise<Player | null> {
  try {
    const baseUrl = getBaseUrl();
    const res = await fetch(`${baseUrl}/api/player/${id}`, {
      cache: 'no-store'
    });

    if (!res.ok) {
      throw new Error('获取玩家数据失败');
    }

    return res.json();
  } catch (error) {
    console.error('获取玩家数据错误:', error);
    return null;
  }
}

// 更新玩家信息
export async function updatePlayer(
  id: string, 
  data: { 
    name: string; 
    region: string; 
    avatar: string;
    region_id?: string;
    region_color?: string;
    is_blacklisted?: boolean;
  }
): Promise<Player> {
  try {
    const baseUrl = getBaseUrl();
    const res = await fetch(`${baseUrl}/api/player/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!res.ok) {
      const error = await res.text();
      throw new Error(error || '更新玩家失败');
    }

    return res.json();
  } catch (error: any) {
    console.error('更新玩家错误:', error);
    throw new Error(error.message || '更新玩家失败');
  }
}

// 更新玩家段位
export async function updatePlayerTier(id: string, tiers: PlayerTier): Promise<Player> {
  try {
    // 准备更新数据
    const updateData: any = {};
    
    // 确保段位值正确传递（整数值表示段位）
    if (tiers.swordTier !== undefined) updateData.swordTier = tiers.swordTier;
    if (tiers.crystalTier !== undefined) updateData.crystalTier = tiers.crystalTier;
    if (tiers.buhcTier !== undefined) updateData.buhcTier = tiers.buhcTier;
    if (tiers.potionTier !== undefined) updateData.potionTier = tiers.potionTier;
    if (tiers.npotTier !== undefined) updateData.npotTier = tiers.npotTier;
    if (tiers.smpTier !== undefined) updateData.smpTier = tiers.smpTier;

    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/api/player/update-tier/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(updateData),
      cache: 'no-store'
    });
    
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(errorText || '更新段位失败');
    }
    
    const result = await response.json();
    
    // 强制刷新以获取最新数据
    setTimeout(() => {
      window.location.reload();
    }, 500);
    
    return result;
  } catch (error: any) {
    console.error('更新段位错误:', error);
    throw new Error(error.message || '更新段位失败');
  }
}

// 删除玩家
export async function deletePlayer(id: string): Promise<void> {
  try {
    const baseUrl = getBaseUrl();
    const res = await fetch(`${baseUrl}/api/player/${id}`, {
      method: 'DELETE',
    });

    if (!res.ok) {
      const error = await res.text();
      throw new Error(error || '删除玩家失败');
    }
  } catch (error: any) {
    console.error('删除玩家错误:', error);
    throw new Error(error.message || '删除玩家失败');
  }
}

// 重置数据库
export async function resetDatabase(): Promise<void> {
  try {
    const baseUrl = getBaseUrl();
    const res = await fetch(`${baseUrl}/api/reset`, {
      method: 'POST',
    });

    if (!res.ok) {
      const error = await res.text();
      throw new Error(error || '重置数据库失败');
    }
  } catch (error: any) {
    console.error('重置数据库错误:', error);
    throw new Error(error.message || '重置数据库失败');
  }
}

// 添加游戏记录
export async function addScore(playerId: number, mode: string) {
  const baseUrl = getBaseUrl();
  const response = await fetch(`${baseUrl}/api/scores`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ playerId, mode }),
  });
  return response.json();
}

// 计算总分数（按模式类型分组求和）
export async function calculateTotalScore(scores: Array<{mode: string}>) {
  return scores.reduce((sum, score) => {
    return sum + (SCORE_MAP[score.mode] || 0);
  }, 0);
}

// 获取所有地区
export async function getRegions() {
  try {
    const baseUrl = getBaseUrl();
    const res = await fetch(`${baseUrl}/api/regions`, {
      cache: 'no-store',
    });

    if (!res.ok) {
      throw new Error('获取地区数据失败');
    }

    return res.json();
  } catch (error) {
    console.error('获取地区错误:', error);
    throw new Error('获取地区失败');
  }
}

// 添加地区
export async function addRegion(regionData: { name: string; color: string }) {
  try {
    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/api/regions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(regionData),
    });
    
    if (!response.ok) {
      const error = await response.text();
      throw new Error(error || '添加地区失败');
    }
    
    const data = await response.json();
    return data.region;
  } catch (error: any) {
    console.error('添加地区错误:', error);
    throw new Error(error.message || '添加地区失败');
  }
}

// 更新地区
export async function updateRegion(id: string, regionData: { name?: string; color?: string }) {
  try {
    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/api/region/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(regionData),
    });
    
    if (!response.ok) {
      const error = await response.text();
      throw new Error(error || '更新地区失败');
    }
    
    const data = await response.json();
    return data.region;
  } catch (error: any) {
    console.error('更新地区错误:', error);
    throw new Error(error.message || '更新地区失败');
  }
}

// 删除地区
export async function deleteRegion(id: string) {
  try {
    const baseUrl = getBaseUrl();
    const response = await fetch(`${baseUrl}/api/region/${id}`, {
      method: 'DELETE',
    });
    
    if (!response.ok) {
      const error = await response.text();
      throw new Error(error || '删除地区失败');
    }
    
    return await response.json();
  } catch (error: any) {
    console.error('删除地区错误:', error);
    throw new Error(error.message || '删除地区失败');
  }
}
